//引入express模块
const express = require("express");
//引入数据库连接模块
const pool = require("../pool.js");
//引入公用函数
//const xsp_fn = require("../others/xsp_fn");
//创建路由器对象
const mR = express.Router();

// 添加评论接口
//接口地址：http://localhost:3333/content/add
mR.post("/add", (req, res, next) => {
    let sql='insert into hbb_message set ?'
    pool.query(sql, [req.body], (err, results) => {
      if (err) {
        res.send( { code: 0, msg: "添加失败！" });
        next(err);
      } else {
        console.log(results);
        res.send({ code: 1, msg: "添加成功!" });
      }
    });
  });
// 查询单个用户的评价
//http://localhost:3333/content/list2
mR.get('/list2', (req, res) => {
    let sql = "select * from hbb_message where to_id =?"
    pool.query(sql, [req.query.to_id], (error, results) => { 
      if (error) throw error;
      // 返回数据到客户端
      res.send({ message: 'ok', code: 200, result: results });
    });
  });
// 查询所有用户的评价
//http://localhost:3333/content/list
mR.get('/list', (req, res) => {
  let sql = "select * from hbb_message "
  pool.query(sql, (error, results) => { 
    if (error) throw error;
    // 返回数据到客户端
    res.send({ message: 'ok', code: 200, result: results });
  });
});
// 修改评论
//3.1接口地址：http://localhost:3333/content/update
mR.put("/update", (req, res, next) => {
    let sql= 'update hbb_message set?where id=?'
    pool.query(sql, [req.body,req.body.id], (err, results) => {
      if (err) {
        next(err);
        return;
      }
      if (results.changedRows) {
        res.send( { code: 1, msg: "修改成功!" });
      } else {
        res.send({ code: 0, msg: "修改失败！" });
      }
    });
  });

// 删除
  //4.1接口地址：http://localhost:3333/content/delete
mR.delete("/delete", (req, res, next) => {
    let sql = 'delete from hbb_message where id=?'
    pool.query(sql, [req.query.id], (err, results) => {
      if (err) {
        next(err);
        return;
      }
      if (results.changedRows) {
        res.send({ code: 0, msg: "删除失败！" });
      } else {
        res.send( { code: 1, msg: "删除成功!" });
      }
    });
  });
  
  //暴露出去
  module.exports = mR;